package com.hejia.alauda.service;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.hejia.alauda.entity.Feedback;
import com.hejia.alauda.entity.Feedback.Status;
import com.hejia.alauda.entity.example.FeedbackExample;
import com.hejia.alauda.persistence.mybatis.FeedbackMapper;
import com.hejia.alauda.utils.Pager;

/**
 * 
 * 用户意见反馈服务实现
 *
 *
 * Created by showone on 2014 下午2:07:51.
 */
@Service
public class FeedbackServiceImpl implements FeedbackService {

	@Resource
	private FeedbackMapper mapper;

	/**
	 * 根据id获取用户反馈
	 * 
	 * @param id
	 * @return
	 */
	public Feedback findFeedbackById(Long id) {
		return mapper.selectByPrimaryKey(id);
	}

	/**
	 * 获取用户反馈列表
	 * 
	 * @param example
	 * @param pager
	 * @return
	 */
	public Pager<Feedback> findFeedbacks(FeedbackExample example,
			Pager<Feedback> pager) {
		pager.setList(mapper.selectByExample(example, pager));
		pager.setTotalCount(mapper.countByExample(example));
		return null;
	}

	/**
	 * 增加用户反馈
	 * 
	 * @param feedback
	 * @return
	 */
	public boolean addFeedback(Feedback feedback) {
		return mapper.insert(feedback) > 0;
	}

	/**
	 * 修改用户反馈
	 * 
	 * @param feedback
	 * @return
	 */
	public boolean modifyFeedback(Feedback feedback) {
		return mapper.updateByPrimaryKey(feedback) > 0;
	}

	@Override
	public Pager<Feedback> findFeedbacksByKeywordAndStatus(String keyword,
			Status status, Pager<Feedback> pager) {
		
		FeedbackExample example = new FeedbackExample();
		example.setOrderByClause("createDate desc");
		
		if(StringUtils.isNotEmpty(keyword)){
			example.appendCriterion("content like ", "%" + keyword + "%");
		}
		if(status != null){
			example.appendCriterion("status = ", status);
		}
		
		pager.setList(this.mapper.selectByExample(example, pager));
		pager.setTotalCount(this.mapper.countByExample(example));
		
		return pager;
	}

	@Override
	public Feedback replyFeedback(Feedback feedback) {
		
		Feedback f = this.mapper.selectByPrimaryKey(feedback.getId());
		
		f.setReplyer(feedback.getReplyer());
		f.setReply(feedback.getReply());
		f.setStatus(Feedback.Status.Processed);
		f.setModifyDate(new Date());
		
		this.mapper.updateByPrimaryKey(f);
		
		return f;
	}
}
